<template>
	<view class="page-container">
		<scroll-view class="form-scroll" scroll-y>
			<view class="form-container">
				<!-- 技术记录标题 -->
				<view class="form-item">
					<text class="form-label required">技术记录标题</text>
					<input class="form-input" style="height: 40px;padding: 0 10px;" v-model="article.title"
						placeholder="请输入技术记录标题" maxlength="100" />
				</view>

				<view class="form-item">
					<text class="form-label required">技术记录封面</text>
					<van-uploader :file-list="fileList" max-count="1" @delete="deleteImages" @after-read="afterRead"
						slot="button" />
				</view>



				<!-- 技术记录分类（按钮式选择） -->
				<view class="form-item">
					<text class="form-label required">技术记录分类</text>
					<view class="category-buttons">
						<view class="category-btn" v-for="(category, index) in categories" :key="index"
							:class="{ 'active': selectedCategoryIndex === index }" @click="selectCategory(index)">
							<text>{{ category }}</text>
						</view>
					</view>
				</view>

				<!-- 技术记录状态 -->
				<view class="form-item">
					<text class="form-label">发布状态</text>
					<view class="status-options">
						<view class="status-option" :class="{ active: article.status == '发布' }"
							@click="statusChange('发布')">
							<text>发布</text>
						</view>
						<view class="status-option" :class="{ active: article.status == '草稿' }"
							@click="statusChange('草稿')">
							<text>草稿</text>
						</view>
					</view>
				</view>

				<!-- 是否推荐 -->
				<view class="form-item">
					<text class="form-label">是否推荐</text>
					<view class="recommend-switch">
						<text class="switch-text">{{ article.isRecommended ? '已推荐' : '未推荐' }}</text>
						<van-switch :checked="article.isRecommended" size="24px" @change="isRecommendedChange"
							active-color="#07c160" />
					</view>
				</view>

				<!-- 技术记录摘要 -->
				<view class="form-item">
					<text class="form-label">技术记录摘要</text>
					<textarea class="form-textarea" v-model="article.excerpt" placeholder="请输入技术记录摘要（可选）" rows="3"
						maxlength="200"></textarea>
					<text class="char-count">{{ article.excerpt.length }}/200</text>
				</view>

				<!-- 技术记录内容 -->
				<view class="form-item">
					<text class="form-label required">技术记录内容</text>
					<div style="padding: 10px 0 ; background-color: #fff;">
						<EditorNameComponent v-if="delay" :text='article.contentHtml || article.content' :onlyId='1'
							@inputEventChange='inputEventChange($event)'>
						</EditorNameComponent>
					</div>
				</view>

				<!-- 底部留白，避免内容被保存按钮遮挡 -->
				<view class="bottom-space"></view>
			</view>
		</scroll-view>

		<!-- 底部固定保存按钮 -->
		<view class="save-bar">
			<view class="save-btn" @click="handleSave">
				<text>保存</text>
			</view>
		</view>
	</view>
</template>

<script>
	import EditorNameComponent from "../../../components/editor/index.vue"
	export default {
		components: {
			EditorNameComponent
		},

		data() {
			return {
				// 判断是新增还是编辑
				isEdit: false,
				// 技术记录ID（编辑时使用）
				articleId: null,
				// 技术记录数据
				article: {
					isRecommended: false, // 是否推荐
					status: '草稿',
					excerpt: ''
				},
				// 分类列表
				categories: ['技术', '编程', '生活', '思考', '创意'],
				// 选中的分类索引
				selectedCategoryIndex: -1,
				delay: false,
				fileList: []
			};
		},
		onLoad(options) {
			// 如果有ID参数，说明是编辑模式
			if (options.id) {
				this.isEdit = true;
				this.articleId = options.id;
				this.loadArticleData();
			} else {
				this.delay = true
			}
		},
		computed: {
			// 选中的分类文本
			selectedCategory() {
				if (this.selectedCategoryIndex >= 0) {
					return this.categories[this.selectedCategoryIndex];
				}
				return this.article.category || '';
			}
		},
		methods: {
			async loadArticleData() {
				this.delay = false
				const submitData = {
					databaseName: 'articles',
					state: 'look',
					_id:this.articleId
				};
				let result = await this.$axios('overallSituation', submitData)

				if (result.code == 200) {
					this.article = result.data[0] || {};
					this.selectedCategoryIndex = this.categories.indexOf(this.article.category);
					if(this.article.coverUrl){
						this.fileList.push({
							url:this.article.coverUrl
						})
					}
				}
				this.delay = true
			},

			// 富文本发生变化
			inputEventChange(e, item) {
				let event = e; 
				this.article.content = event.text;
				this.article.contentHtml = event.html;
			},

			// 返回列表页
			handleBack() {
				uni.navigateBack();
			},

			// 保存技术记录
			async handleSave() {
				// 表单验证
				if (!this.article.title) {
					this.$showToast('请输入技术记录标题')
					return;
				}

				if (this.selectedCategoryIndex === -1) {
					this.$showToast('请选择技术记录分类')
					return;
				}

				if (!this.article.content) {
					this.$showToast('请输入技术记录内容')
					return;
				}
				
				if (
					this.fileList.length != 0 &&
					!this.fileList[0].url.includes("https://")
				) {
					let imageRes = await uniCloud.uploadFile({
						filePath: this.fileList[0].url,
						cloudPath: "技术记录封面" + this.$getFileExtensionName(this.fileList[0].url),
						header: {
							"Content-Type": "multipart/form-data",
						},
					});
				
					this.article.coverUrl = imageRes.fileID;
				}

				// 更新选中的分类
				this.article.category = this.categories[this.selectedCategoryIndex];

				// 准备提交的数据
				const submitData = {
					...this.article,
					databaseName: 'articles',
					state: this.article._id ? 'update' : 'add',
					createTime:this.$getTime('yyyy-MM-DD'),
					isRecommendedName:this.article.isRecommended ? '是' : '否'
				};

				// 调用接口保存
				let result = await this.$axios('overallSituation', submitData)
				if (result.code == 200) {
					this.$showToast(`${this.article._id ? '更新成功' : '创建成功'}`)
					uni.navigateBack();
				} else {
					this.$showToast("操作失败")
				}
			},

			// 文件上传
			afterRead(e) {
				this.fileList.push({
					url: e.detail.file.url,
				});
			},

			// 删除图片回调函数
			deleteImages(e) {
				this.fileList.splice(e.detail.index, 1);
			},

			// 选择分类
			selectCategory(index) {
				this.selectedCategoryIndex = index;
				this.article.category = this.categories[index];
			},

			isRecommendedChange(e) {
				this.article.isRecommended = e.detail
			},

			// 点击状态
			statusChange(e) {
				this.article.status = e
			}
		}
	};
</script>


<style scoped>
	.page-container {
		font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, sans-serif;
		background-color: #f5f5f7;
		color: #1d1d1f;
		height: 100vh;
		position: relative;
	}

	/* 导航栏样式 */
	.navbar {
		background-color: #ffffff;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
		position: sticky;
		top: 0;
		z-index: 99;
	}

	.navbar-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 100rpx;
		padding: 0 30rpx;
		box-sizing: border-box;
	}

	.nav-left,
	.nav-right {
		width: 120rpx;
	}

	.nav-left {
		text-align: left;
	}

	.nav-right {
		text-align: right;
	}

	.placeholder {
		width: 80rpx;
	}

	.back-btn {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		color: #007aff;
		font-size: 30rpx;
		background: transparent;
		border: none;
		padding: 0;
	}

	.icon {
		margin-right: 6rpx;
	}

	.nav-title {
		font-size: 34rpx;
		font-weight: 600;
		color: #1d1d1f;
	}

	/* 滚动区域 */
	.form-scroll {
		width: 100%;
		height: 89vh;
	}

	/* 表单容器 */
	.form-container {
		padding: 30rpx;
	}

	/* 表单项目 */
	.form-item {
		margin-bottom: 40rpx;
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		color: #1d1d1f;
		margin-bottom: 14rpx;
		font-weight: 500;
	}

	.required::after {
		content: '*';
		color: #ff3b30;
		margin-left: 6rpx;
	}

	.form-input,
	.form-textarea {
		width: 100%;
		padding: 24rpx;
		box-sizing: border-box;
		background-color: #fff;
		border: 1px solid #e2e2e2;
		border-radius: 12rpx;
		font-size: 28rpx;
		color: #1d1d1f;
		box-sizing: border-box;
		transition: border-color 0.2s;
	}

	.form-input:focus,
	.form-textarea:focus {
		border-color: #007aff;
		outline: none;
	}

	.form-input::placeholder,
	.form-textarea::placeholder {
		color: #999;
	}

	.form-textarea {
		min-height: 160rpx;
		resize: vertical;
		line-height: 1.6;
	}

	.char-count {
		display: block;
		text-align: right;
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	/* 分类按钮样式 */
	.category-buttons {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.category-btn {
		padding: 16rpx 28rpx;
		background-color: #ffffff;
		border: 1px solid #e2e2e2;
		border-radius: 30rpx;
		font-size: 26rpx;
		color: #444;
		white-space: nowrap;
		transition: all 0.2s;
	}

	.category-btn.active {
		background-color: #007aff;
		color: #ffffff;
		border-color: #007aff;
		box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.25);
	}

	.category-btn:not(.active):hover {
		background-color: #f5f5f7;
	}

	/* 状态选择 */
	.status-options {
		display: flex;
		gap: 20rpx;
	}

	.status-option {
		flex: 1;
		height: 88rpx;
		background-color: #fff;
		border: 1px solid #e2e2e2;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #444;
		transition: all 0.2s;
	}

	.status-option.active {
		background-color: #f0f7ff;
		border-color: #007aff;
		color: #007aff;
		font-weight: 500;
	}

	.status-option:not(.active):hover {
		background-color: #f5f5f7;
	}

	/* 是否推荐开关 */
	.recommend-switch {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #fff;
		border: 1px solid #e2e2e2;
		border-radius: 12rpx;
		padding: 0 24rpx;
		height: 88rpx;
	}

	.switch-text {
		font-size: 28rpx;
		color: #1d1d1f;
	}

	.switch-toggle {
		width: 60rpx;
		height: 36rpx;
		background-color: #e2e2e2;
		border-radius: 18rpx;
		position: relative;
		transition: background-color 0.2s;
	}

	.switch-toggle.active {
		background-color: #007aff;
	}

	.switch-knob {
		width: 32rpx;
		height: 32rpx;
		background-color: white;
		border-radius: 50%;
		position: absolute;
		top: 2rpx;
		left: 2rpx;
		transition: transform 0.2s;
	}

	.switch-toggle.active .switch-knob {
		transform: translateX(24rpx);
	}

	/* 底部留白 */
	.bottom-space {
		height: 120rpx;
	}

	/* 底部保存按钮栏 */
	.save-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		background-color: #ffffff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 98;
	}

	.save-btn {
		width: 100%;
		height: 90rpx;
		background-color: #007aff;
		color: #ffffff;
		border-radius: 45rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		font-weight: 500;
		box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.25);
		transition: background-color 0.2s;
	}

	.save-btn:active {
		background-color: #0066cc;
	}
</style>